package com.jerkin.consumer.proxy;

import com.jerkin.coder.DecoderHelper;
import com.jerkin.coder.EncoderHelper;
import com.jerkin.consumer.handler.RpcClientHandler;
import com.jerkin.executor.ExecutoreConsumerService;
import com.jerkin.model.User;
import com.jerkin.request.RpcRequest;
import com.jerkin.serial.HessianSerializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @version V1.0
 * @ClassName: RpcConsumerProxy
 * @Description:
 * @author: huhongzhi
 * @date: 2021/6/20 23:18
 */
public class RpcConsumerProxy {

    private static RpcClientHandler rpcClientHandler;

    public static Object createProxy(Class<?> serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        if (rpcClientHandler == null) {
                            initClient();
                        }

                        String className = method.getDeclaringClass().getSimpleName();
                        String methodName = method.getName();
                        Class<?>[] parameterTypes = method.getParameterTypes();

                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setClassName(className);
                        rpcRequest.setMethodName(methodName);
                        rpcRequest.setParameterTypes(parameterTypes);
                        rpcRequest.setParameters(args);
                        rpcClientHandler.setParam(rpcRequest);
                        Object result = ExecutoreConsumerService.get().submit(rpcClientHandler).get();
                        return result;
                    }
                });
    }

    public static void initClient() throws InterruptedException {
        // 1) 初始化 userClientHandler
        rpcClientHandler = new RpcClientHandler();
        // 2) 创建连接池对象
        EventLoopGroup group = new NioEventLoopGroup();
        // 3) 创建客户端的引导对象
        Bootstrap bootstrap = new Bootstrap();
        // 4) 配置启动引导对象
        bootstrap.group(group)
                // 设置通道为NIO
                .channel(NioSocketChannel.class)
                // 设置请求协议为TCP
                .option(ChannelOption.TCP_NODELAY, true)
                // 监听channel 并初始化
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        // 获取 ChannelPipeline
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        // 设置编码
                        // pipeline.addLast(new StringEncoder());
                        // pipeline.addLast(new StringDecoder());

                        pipeline.addLast(new EncoderHelper(RpcRequest.class, new HessianSerializer()));
                        pipeline.addLast(new DecoderHelper(User.class,new HessianSerializer()));
                        pipeline.addLast(rpcClientHandler);
                    }
                });
        bootstrap.connect("127.0.0.1", 9999).sync();
        System.out.println("rpc-consumer已启动...");
    }
}
